package com.blogs.ui;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.blogs.component.BaseActivity;
import com.blogs.component.IngFeedAdapter;
import com.blogs.component.RefreshListView;
import com.blogs.component.RefreshListView.OnMoreListener;
import com.blogs.component.RefreshListView.OnRefreshListener;
import com.blogs.entity.AppEnums.IngPublicType;
import com.blogs.entity.IngComFeed;
import com.blogs.entity.IngFeed;
import com.blogs.service.DeleteIng;
import com.blogs.service.GetIngLine;
import com.blogs.tools.DBSharedPreferences;
import com.blogs.tools.FormatTime;
import com.blogs.tools.LoadingGif;
import com.blogs.tools.MsgCountToast;
import com.blogs.ui.FavoriteActivity.getDataMethod;
import com.cnblogs.R;

public class IngActivity extends BaseActivity implements OnClickListener, OnItemClickListener, OnItemLongClickListener {
	private DBSharedPreferences sp;
	private RelativeLayout title_top_bg;
	private Button title_comment_write;
	private TextView title_include_title;
	private Button title_include_back;
	private LinearLayout ing_list_body;
	private LoadingGif loadingGif;
	private ArrayList<IngFeed> feedList;
	private RefreshListView listView;
	private IngFeedAdapter adapter;

	private ProgressDialog proDdialog;
	private int currpage = 1;
	private IngPublicReceiver ingPublicReceiver;
	private IngComDelReceiver ingComDelReceiver;
	private Toast toast;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inglayout);
		sp = new DBSharedPreferences(this);
		ViewGroup headview = (ViewGroup) findViewById(R.id.main_title_include);
		title_top_bg = (RelativeLayout) headview;
		title_include_title = (TextView) headview.findViewById(R.id.title_include_title);
		title_include_back = (Button) headview.findViewById(R.id.title_include_back);
		title_comment_write = (Button) headview.findViewById(R.id.title_comment_write);
		title_include_title.setText("闪存");
		title_include_back.setVisibility(View.VISIBLE);
		title_include_back.setOnClickListener(this);
		title_comment_write.setVisibility(View.VISIBLE);
		title_comment_write.setOnClickListener(this);

		ing_list_body = (LinearLayout) findViewById(R.id.ing_list_body);
		listView = new RefreshListView(this);
		listView.setCacheColorHint(Color.TRANSPARENT);
		listView.setOnItemClickListener(this);
		listView.setOnItemLongClickListener(this);
		listView.setonMoreListener(new OnMoreListener() {

			public void onGetMore() {
				// TODO Auto-generated method stub
				GetMoreData();
			}
		});
		listView.setonRefreshListener(new OnRefreshListener() {

			public void onRefresh() {
				// TODO Auto-generated method stub
				// 刷新
				RefreshData();
			}
		});
		loadingGif = new LoadingGif(this, listView, ing_list_body, sp);
		loadingGif.setOnReloadListener(new LoadingGif.OnReloadListener() {

			public void onClick() {
				// TODO Auto-generated method stub
				loadingGif.showLoading();
				RefreshData();
			}
		});
		this.requestData();
		ingPublicReceiver = new IngPublicReceiver();// 设置广播接收
		IntentFilter skinFilter = new IntentFilter();
		skinFilter.addAction("IngPublicReceiver");
		registerReceiver(ingPublicReceiver, skinFilter);

		ingComDelReceiver = new IngComDelReceiver();// 设置闪存删除广播接收
		IntentFilter skinFilter2 = new IntentFilter();
		skinFilter2.addAction("IngComDelReceiver");
		registerReceiver(ingComDelReceiver, skinFilter2);

		this.InitSkin();
		this.InitProDailog();
	}

	private void InitSkin() {
		if (sp.GetIsDarkState()) {
			title_top_bg.getBackground().setLevel(2);
			ing_list_body.getBackground().setLevel(2);
		} else {
			title_top_bg.getBackground().setLevel(1);
			ing_list_body.getBackground().setLevel(1);
		}
	}

	private void InitProDailog() {
		proDdialog = new ProgressDialog(this);
		proDdialog.setIndeterminate(true);
		proDdialog.setCancelable(true);
		proDdialog.setMessage("正在删除闪存...");
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == title_include_back) {
			this.finish();
		} else if (v == title_comment_write) {
			Intent intent = new Intent();
			intent.setClass(IngActivity.this, IngPublicActivity.class);
			startActivity(intent);
		}
	}

	private void requestData() {
		loadingGif.showLoading();
		this.sendTimeLine("", "", getDataMethod.init);
	}

	private void RefreshData() {
		currpage = 1;
		String sinceid = feedList != null && feedList.size() != 0 ? feedList.get(0).id : "";
		this.sendTimeLine(sinceid, "", getDataMethod.pull);
	}

	private void GetMoreData() {
		currpage++;
		String maxid = feedList != null && feedList.size() != 0 ? feedList.get(feedList.size() - 1).id : "";
		this.sendTimeLine("", maxid, getDataMethod.more);
	}

	public void updateRequestData() {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		} else {
			adapter = new IngFeedAdapter(this, feedList);
			listView.setAdapter(adapter);
		}
		loadingGif.showData();
		listView.onRefreshComplete();
		listView.onMoreComplete();
	}

	private void sendTimeLine(final String since_id, String max_id, final getDataMethod gdm) {
		new GetIngLine(sp.GetSessionID(), currpage, since_id, max_id, new GetIngLine.IMsgCallBack() {

			public void onSuccess(ArrayList<IngFeed> feeds) {
				// TODO Auto-generated method stub
				if (feedList == null)
					feedList = new ArrayList<IngFeed>();
				if (gdm == getDataMethod.init || gdm == getDataMethod.pull) {
					feedList.clear();
				}
				for (int i = 0; i < feeds.size(); i++) {
					feedList.add(feeds.get(i));
					Log.i("mying", feeds.get(i).author);
				}
				if (!since_id.equals("")) {
					int fcount = 0;
					for (IngFeed f : feeds) {
						if (since_id.equals(f.id)) {
							break;
						}
						fcount++;
					}
					MsgCountToast.ShowToast(IngActivity.this, fcount);
				}
				updateRequestData();
			}

			public void onFailed() {
				// TODO Auto-generated method stub
				loadingGif.showFiale();
				Log.i("mying", "错误");
			}
		}).loadData();
	}

	public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
		// TODO Auto-generated method stub
		Intent hintent = new Intent();
		hintent.setClass(IngActivity.this, IngPublicActivity.class);
		hintent.putExtra("position", position - 1);
		hintent.putExtra("ContentId", Integer.parseInt(feedList.get(position - 1).id));
		hintent.putExtra("ReplyTo", Integer.parseInt(feedList.get(position - 1).author_id));
		hintent.putExtra("AtAuthor", feedList.get(position - 1).author);
		hintent.putExtra("FromMsg", feedList.get(position - 1).body);
		hintent.putExtra("ParentCommentId", 0);
		startActivity(hintent);
	}

	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
		// TODO Auto-generated method stub
		String[] items = { "查看详情", "回复", "取消" };
		String[] items_d = { "查看详情", "回复", "删除", "取消" };
		final String[] f_items;
		if (!sp.GetNickName().equals("") && sp.GetNickName().equals(feedList.get(position - 1).author)
				&& !feedList.get(position - 1).id.equals("0")) {
			f_items = items_d;
		} else {
			f_items = items;
		}
		new AlertDialog.Builder(IngActivity.this).setItems(f_items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (f_items[which].equals("查看详情")) {
					Intent mintent = new Intent();
					mintent.setClass(IngActivity.this, IngDetail.class);
					mintent.putExtra("position", position - 1);
					mintent.putExtra("ingid", feedList.get(position - 1).id);
					mintent.putExtra("author", feedList.get(position - 1).author);
					mintent.putExtra("author_id", feedList.get(position - 1).author_id);
					mintent.putExtra("avatar", feedList.get(position - 1).avatar);
					mintent.putExtra("com_time", feedList.get(position - 1).com_time);
					mintent.putExtra("body", feedList.get(position - 1).body);
					startActivity(mintent);
				} else if (f_items[which].equals("回复")) {
					Intent hintent = new Intent();
					hintent.setClass(IngActivity.this, IngPublicActivity.class);
					hintent.putExtra("position", position - 1);
					hintent.putExtra("ContentId", Integer.parseInt(feedList.get(position - 1).id));
					hintent.putExtra("ReplyTo", Integer.parseInt(feedList.get(position - 1).author_id));
					hintent.putExtra("AtAuthor", feedList.get(position - 1).author);
					hintent.putExtra("FromMsg", feedList.get(position - 1).body);
					hintent.putExtra("ParentCommentId", 0);
					startActivity(hintent);
				} else if (f_items[which].equals("删除")) {
					new AlertDialog.Builder(IngActivity.this).setTitle("删除闪存").setMessage("确定吗？")
							.setPositiveButton("是", new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									proDdialog.show();
									new DeleteIng(sp.GetSessionID(), feedList.get(position - 1).id,
											new DeleteIng.IMsgCallBack() {

												public void onSuccess() {
													// TODO Auto-generated
													// method stub
													showToast("删除闪存成功");
													feedList.remove(position - 1);
													adapter.notifyDataSetChanged();
													proDdialog.hide();
												}

												public void onFailed(String err) {
													// TODO Auto-generated
													// method stub
													showToast("删除闪存失败," + err);
													proDdialog.hide();
												}
											}).Del();
								}
							}).setNegativeButton("否", null).show();
				}
			}
		}).create().show();
		return false;
	}

	private void showToast(String text) {
		if (toast == null) {
			toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		} else {
			toast.setText(text);
			toast.setDuration(Toast.LENGTH_SHORT);
		}
		toast.show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(ingPublicReceiver);
		unregisterReceiver(ingComDelReceiver);
	}

	class IngComDelReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			int position = intent.getIntExtra("position", 0);
			String com_time = intent.getStringExtra("com_time");
			String author = intent.getStringExtra("author");
			ArrayList<IngComFeed> comfeeds = feedList.get(position).com_feeds;
			for (int i = 0; i < comfeeds.size(); i++) {
				Log.i("ing_com_time", comfeeds.get(i).com_time + "-->" + com_time);
				if (FormatTime.timeSpace(com_time, comfeeds.get(i).com_time) < 40
						&& comfeeds.get(i).author.equals(author)) {
					comfeeds.remove(i);
					adapter.notifyDataSetChanged();
					break;
				}
			}
		}
	}

	class IngPublicReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {

			if (intent.getIntExtra("IngPublicType", 0) == IngPublicType.New) {
				IngFeed feed = new IngFeed();
				feed.id = "0";
				feed.avatar = intent.getStringExtra("avatar");
				feed.author = intent.getStringExtra("author");
				feed.author_id = intent.getStringExtra("author_id") == null ? "0" : intent.getStringExtra("author_id");
				feed.body = intent.getStringExtra("Content");
				feed.com_time = intent.getStringExtra("comment_time");
				feed.has_more_com = 0;
				feedList.add(0, feed);
				updateRequestData();
				listView.setSelection(0);
			} else if (intent.getIntExtra("IngPublicType", 0) == IngPublicType.Com
					&& intent.getIntExtra("position", -1) != -1) {
				Log.i("IngPublicType", intent.getIntExtra("IngPublicType", 0) + "");
				IngFeed feed = feedList.get(intent.getIntExtra("position", -1));
				IngComFeed comfeed = new IngComFeed();
				comfeed.id = "0";
				comfeed.parent_id = intent.getIntExtra("ContentId", 0) + "";
				comfeed.author = intent.getStringExtra("author");
				comfeed.author_id = intent.getStringExtra("author_id") == null ? "0" : intent
						.getStringExtra("author_id");
				comfeed.content = intent.getStringExtra("Content");
				comfeed.com_time = intent.getStringExtra("comment_time");
				feed.has_more_com = feed.com_feeds.size() >= 15 ? 1 : 0;
				feed.com_feeds.add(0, comfeed);
				adapter.notifyDataSetChanged();
			}
		}
	}
}
